package cn.lucky.datastructure.queue;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author lingpeng.jiang
 * @create 2021-01-31-16:41 队列
 */
public class ConsumerQueue {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue(5);
        myQueue.enterQueue(1);
        myQueue.enterQueue(2);
        myQueue.enterQueue(3);
        myQueue.enterQueue(4);
        myQueue.enterQueue(5);
        myQueue.enterQueue(6);
        while (!myQueue.isEmpty()){
            System.out.print(myQueue.outQueue() + " ");
        }
        System.out.println(myQueue.isFull());
        System.out.println(myQueue.isEmpty());
    }

}

class MyQueue{

    private Object[] elementData;

    /**
     * 默认初始化一个空队列
     */
    private static final Object[] DEFAULT_ELEMENT = {};

    /**
     * 队列默认长度
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 默认队头
     */
    private static final int DEFAULT_FRONT = 0;

    /**
     * 默认队尾
     */
    private static final int DEFAULT_REAR = -1;

    private static final int DEFAULT_SIZE = 0;

    /**
     * 队列头指针
     */
    private int front;

    /**
     * 队列尾指针
     */
    private int rear;

    private int maxSize;

    private int size;

    public MyQueue(int initialCapacity){
        this.maxSize = initialCapacity;
        this.front = 0;
        this.rear = -1;
        this.elementData = new Object[initialCapacity];
        this.size = 0;
    }

    public MyQueue(){
        this.elementData = DEFAULT_ELEMENT;
        this.front = DEFAULT_FRONT;
        this.rear = DEFAULT_REAR;
        this.maxSize = DEFAULT_CAPACITY;
        this.size = DEFAULT_SIZE;
    }


    /**
     * 入队
     * @param data
     * @return
     */
    public boolean enterQueue(Object data){
        if (isFull()){
            throw new IndexOutOfBoundsException("this queue is full");
        }else {
            if (rear == (maxSize - 1)){
                rear = 0;
            }else {
                ++rear;
            }
            elementData[rear] = data;
            size++;
        }
        return true;
    }


    /**
     * 出队
     * @return
     */
    public Object outQueue(){
        Object outQueue = null;
        if (isEmpty()){
            throw new RuntimeException("this queue is empty");
        } else {
           if (front == (maxSize - 1)){
                outQueue = elementData[front--];
           }else{
               outQueue = elementData[front++];
           }
           size--;
           return outQueue;
        }
    }

    public Object getFront(){
        if (isEmpty()){
            throw new RuntimeException("this queue is empty");
        }
        return elementData[front];
    }

    public boolean isEmpty(){
        return this.size == 0;
    }

    public boolean isFull(){
        return this.size == (this.maxSize - 1);
    }
}